package com.wellview.template.view;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.wellview.template.BaseActivity;
import com.wellview.template.Constant;
import com.wellview.template.R;
import com.wellview.template.logger.Logger;
import com.wellview.template.utils.EventCenter;
import com.wellview.template.utils.FileUtil;
import com.wellview.template.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

import static android.os.Build.VERSION_CODES.M;

/**
 * Created by 54757 on 2017/12/19.
 */

public class SelectPhotoActivity extends BaseActivity {
    private static final int REQUEST_CHOOSE_PICTURE = 0xff25;
    private static final int REQUEST_TAKE_PICTURE = 0xff27;
    private static final int CROP_REQUEST_CODE = 0xff26;
    private String filePath = "";

    @BindView(R.id.take_photo)
    Button takePhoto;
    @BindView(R.id.select_picture)
    Button selectPicture;
//    @BindView(R.id.iv_pic)
//    ImageView ivPic;

    private Uri imageUri;
    private Uri dstUri;
    private String extra ;
    private File tempFile;

    @Override
    protected void beforeShow(Bundle savedInstanceState) {
        Intent intent = getIntent();
        String extra = intent.getStringExtra("extra");
        Logger.i(TAG, "extra is " + extra);
        this.extra = extra;
    }

    @Override
    public void bindView() {
        setContentView(R.layout.activity_choose_photos);
    }

    @Override
    public void findAllViews() {

    }

    @Override
    public void setAllListeners() {

    }

    @Override
    public void doProcess() {

    }

    @OnClick({R.id.take_photo,R.id.select_picture,R.id.background})
    public void onViewClicked(View v) {
        switch (v.getId()){
            case R.id.take_photo:
                openCamera();
                break;
            case R.id.select_picture:
                choosePhoto();
                break;
            case R.id.background:
                finish();
                break;
        }
    }

    public void openCamera() {
        if (!EasyPermissions.hasPermissions(this,Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            checkPermissions(Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return;
        }
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (FileUtil.isCanUseSDCard()) {
            File imagePath = new File(this.getExternalCacheDir(), "");
            tempFile = new File(imagePath, "before.png");
            File dstFile = new File(imagePath, "dist.png");
            dstUri = Uri.fromFile(dstFile);
            if (currentapiVersion < 24) {
                // 从文件中创建uri
                imageUri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            } else {
//                File imagePath = new File(this.getExternalCacheDir(), "");
                imageUri = Uri.fromFile(tempFile);
                Uri uri = FileProvider.getUriForFile(this, "com.wellview.template.fileprovider", tempFile);
                //添加权限
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                Logger.i(TAG,"open 7.0 uri is "+ uri.toString());
            }
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        startActivityForResult(intent, REQUEST_TAKE_PICTURE);
    }

    private void choosePhoto() {
        if (!EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            checkPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            return;
        }

        Intent intent = new Intent();
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {//4.4及以上    intent2.setAction(Intent.ACTION_OPEN_DOCUMENT);
            intent.setAction(Intent.ACTION_PICK);
            intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        } else {//4.4以下
            intent.setAction(Intent.ACTION_GET_CONTENT);
        }
        if (FileUtil.isCanUseSDCard()) {
            File imagePath = new File(this.getExternalCacheDir(), "");
            tempFile = new File(imagePath, "before.png");
            File dstFile = new File(imagePath, "dist.png");
            dstUri = Uri.fromFile(dstFile);
            if (currentapiVersion < 24) {
                // 从文件中创建uri
                imageUri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            } else {
//                //兼容android7.0 使用共享文件的形式
//                ContentValues contentValues = new ContentValues(1);
//                contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
//                //检查是否有存储权限，以免崩溃
//                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                        != PackageManager.PERMISSION_GRANTED) {
//                    //申请WRITE_EXTERNAL_STORAGE权限
//                    showToast("请开启存储权限");
//                    return;
//                }
//                imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

                imageUri = Uri.fromFile(tempFile);
                Uri uri = FileProvider.getUriForFile(this, "com.wellview.template.fileprovider", tempFile);
                //添加权限
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                Logger.i(TAG,"choose 7.0 uri is "+ uri.toString());
            }
        }
        startActivityForResult(intent, REQUEST_CHOOSE_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CHOOSE_PICTURE && resultCode == RESULT_OK){
            Uri uri = data.getData();
            startImageZoom(uri);
        }
        if (requestCode ==REQUEST_TAKE_PICTURE && resultCode == RESULT_OK){
            Logger.i(TAG,"imageUri is "+imageUri);
            Logger.i(TAG,"tempFile is "+tempFile.getAbsolutePath());
            startImageZoom(imageUri);
        }
        if (requestCode == CROP_REQUEST_CODE && resultCode == RESULT_OK){
            Logger.w(TAG,"crop: imageUri "+dstUri.toString());
            File fileByUri = FileUtil.getFileByUri(this, dstUri);
            Logger.i(TAG,"file len is: crop"+fileByUri.length());
//            ivPic.setImageBitmap(BitmapFactory.decodeFile(fileByUri.getAbsolutePath()));
            EventBus.getDefault().post(new EventCenter(new String[]{dstUri.toString()}, Constant.MESSAGE_CHOOSE_PHOTO));
            finish();
        }

    }

    /**
     * 剪裁图片
     *
     */
    private void startImageZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, dstUri);
        Logger.i(TAG,"dstUri is "+dstUri);
        startActivityForResult(intent, CROP_REQUEST_CODE);
    }
}
